package com.partsoft.dits.message;

import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

@SuppressWarnings({"unchecked"})
public class BaseMessageEntity implements MessageEntity {
	
	private MessageEntity ownerMessageEntity = null;
	
	private BaseMessageHeader header = new BaseMessageHeader();
	
	private List<MessageDataItem> datas = Collections.EMPTY_LIST;
	
	public MessageEntity getOwner() {
		return ownerMessageEntity;
	}
	
	public void setOwner(MessageEntity ownerMessageEntity) {
		this.ownerMessageEntity = ownerMessageEntity;
	}

	public MessageHeader getHeader() {
		return header;
	}
	
	public void setHeader(MessageHeader header) {
		this.header = new BaseMessageHeader(header);
	}

	public boolean isTop() {
		return getOwner() == null;
	}
	
	protected List<MessageDataItem> getRawDatas() {
		if (datas == Collections.EMPTY_LIST) datas = new LinkedList<MessageDataItem>();
		return datas;
	}

	public MessageDataItem[] getDatas() {
		return datas.toArray(new MessageDataItem[0]);
	}
	
	public boolean addData(MessageDataItem item) {
		Assert.notNull(item);
		Assert.isTrue(ObjectUtils.nullSafeEquals(item.getOwner(), this), "不能添加非本消息实体的消息数据。");
		return getRawDatas().add(item);
	}
	
	public boolean hasData() {
		return !CollectionUtils.isEmpty(datas);
	}

	@Override
	public String toString() {
		return "entity [" + getHeader() + ", rows={" + Arrays.toString(getDatas()) + "}]";
	}
}
